<template>
  <div
    style="display: flex; height: 100%; border-radius: 10px; overflow: hidden"
  >
    <div class="box" style="width: 120px; background-color: #000">
      <ul>
        <li>全部店铺</li>
      </ul>
    </div>
    <div class="boxs" style="width: 200px; background-color: #eee">
      <div
        style="
          display: flex;
          height: 40px;
          justify-content: center;
          align-items: center;
        "
      >
        <el-button
          @click="dialogVisibles = true"
          size="small"
          style="color: #fff; font-size: 12px"
          type="primary"
          color="rgb(78 168 185)"
          round
          >新建聊天</el-button
        >
      </div>
      <ul>
        <el-dialog
          v-model="dialogVisibles"
          title="新建聊天"
          width="500"
          :before-close="handleClose"
        >
          <el-form
            label-position="top"
            :model="ruleForm"
            :rules="ruless"
            ref="ruleForms"
            label-width="120px"
            class="demo-ruleForm"
          >
            <el-form-item prop="posting_number">
              <template #label>
                <span style="font-size: 12px; font-weight: 700; color: #000">
                  发货识别码 <i class="el-icon-question"></i
                ></span>
              </template>
              <el-input v-model="ruleForm.posting_number"></el-input>
            </el-form-item>
            <el-form-item>
              <p style="text-align: center; width: 100%">
                <el-button
                  style="margin-top: 30px; color: #fff; font-size: 12px"
                  type="primary"
                  color="rgb(78 168 185)"
                  round
                  @click="submitForm"
                  >确定</el-button
                >
              </p>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer"></div>
          </template>
        </el-dialog>

        <li
          :class="{se: que == item.chat_id}"
          @click="daili(item.chat_id)"
          v-for="item in [...chatList]"
          :key="item.chat_id"
        >
          <div
            style="display: flex; justify-content: center; align-items: center"
          >
            <span style="margin-right: 3px">
              <span>
                {{
                  chatTypeDict[item.chat_type]
                    ? chatTypeDict[item.chat_type]
                    : item.chat_type
                }}</span
              >
            </span>
            <p
              style="
                display: flex;
                align-items: center;
                justify-content: center;
                width: 15px;
                font-size: 10px;
                height: 15px;
                border-radius: 50%;
                padding: 3px;
                margin-left: 3px;
                background-color: rgb(244 225 229);

                color: rgb(218 1 64);
              "
            >
              {{ item.unread_count }}
            </p>
          </div>
          <div class="ni" style="font-size: 10px; color: #7c7b7b">
            {{ gdaTes(item.created_at) }}
          </div>
        </li>
      </ul>
    </div>

    <div class="chat_frame_box">
      <header class="header">客服</header>
      <main class="chat_frame_body">
        <div class="left">
          <div v-if="msgContent.length" ref="chatBox" class="chat_box">
            <div
              v-for="(item, idx) in msgContent"
              :key="idx + item"
              class="msg_li"
              :class="{myself: item.user.id == yonghu.clientId}"
            >
              <img
                v-if="item.isMe"
                src="../../assets/customer_service.png"
                alt="头像"
                class="head_img"
              />
              <img
                v-else
                alt="头像"
                src="../../assets/user_head.png"
                class="head_img"
              />

              <div class="details" v-html="markeds(item.data[0])"></div>
            </div>
          </div>
          <div v-else ref="chatBox" class="chat_box"></div>
          <div class="input_box">
            <el-input
              v-model.trim="inputMsg"
              type="textarea"
              placeholder="请输入..."
              resize="none"
              @keydown.enter="transmitMsg"
            />

            <div class="btn_box">
              <span style="font-weight: 700">
                <el-checkbox v-model="checked1"> 发送后自动翻译 </el-checkbox>
              </span>
              <el-button
                type="primary"
                size="mini"
                style="color: #fff; margin: 10px 0; font-size: 12px"
                color="rgb(78 168 185)"
                @click="transmitMsg"
                >发送</el-button
              >
            </div>

            <!-- <el-button @click="addOtherMsg">点击增加别人信息</el-button> -->
          </div>
        </div>
        <div class="right">
          <h4
            class="common_question_title"
            style="display: flex; justify-content: space-between"
          >
            <span>快捷回复</span>
            <span class="xin" @click="xinzz">新增</span>

            <!-- <img src="" alt=""> -->
          </h4>
          <ul class="question_list">
            <li v-for="item in huiData" :key="item.templateId" class="li">
              <span @click="transmitMsg(e, item.content)" class="tl">
                {{ item.title }}
                <img
                  src="../../assets/hot_fill.png"
                  class="hot_fill"
                  alt="热门"
              /></span>
              <span style="font-size: 12px; color: #999">
                <span class="des" style="margin-right: 5px">
                  <el-popconfirm
                    width="220"
                    confirm-button-text="OK"
                    cancel-button-text="不了"
                    @confirm="dele(item)"
                    :icon="InfoFilled"
                    icon-color="#626AEF"
                    title="确定删除吗？"
                  >
                    <template #reference>
                      <el-icon><Delete /></el-icon>
                    </template>
                  </el-popconfirm>
                </span>

                <el-icon @click="bianji(item)" class="des"><Edit /></el-icon>
              </span>
            </li>
          </ul>
        </div>
      </main>
    </div>

    <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="500">
      <span style="font-weight: 700"
        >{{ kong == "zeng" ? "新增" : "编辑" }}快捷回复</span
      >

      <div style="width: 300px; margin: auto; margin-top: 30px">
        <el-form
          label-position="top"
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="标题" prop="title">
            <template #label>
              <span style="font-size: 12px; font-weight: 700; color: #000">
                标题 <i class="el-icon-question"></i
              ></span>
            </template>
            <el-input v-model="form.title" maxlength="30" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <template #label>
              <span style="font-size: 12px; font-weight: 700; color: #000">
                内容 <i class="el-icon-question"></i
              ></span>
            </template>
            <el-input v-model="form.content" maxlength="11" />
          </el-form-item>
        </el-form>
      </div>
      <div style="text-align: center">
        <el-button
          type="primary"
          size="mini"
          @click="submit"
          round
          color="rgb(78 168 185)"
          style="width: 80px; color: #fff; margin-bottom: 20px; font-size: 12px"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {ElNotification} from "element-plus";
import {h} from "vue";
import {marked} from "marked"; // 使用命名导入

import {
  getHui,
  fasong,
  getshop,
  zenkuai,
  deletekui,
  putekui,
  getCList,
  xinjiala,
  chatHistory,
  yidu,
} from "../../api/index";
import md5 from "js-md5";
import {jsonp} from "vue-jsonp";
import {gdaTe} from "../../utils/data";
export default {
  data() {
    return {
      ruleForm: {
        posting_number: null,
      },
      ruless: {
        posting_number: [
          {required: true, message: "识别码不能为空", trigger: "blur"},
        ],
      },
      chatList: [],
      dialogVisibles: false,
      form: {title: "", content: ""},
      chatTypeDict: {
        Seller_Notification_Major: "卖家主要通知",
        Seller_Marketplace_Promo: "卖家市场促销",
        Seller_Notification_FBS: "卖家通知 FBS",
        Seller_Notification_Content: "卖家通知内容",
        Seller_Paid_Brands: "卖家付费品牌",
        Seller_Notification_FBP: "卖家通知 FBP",
        Seller_Online_Training: "卖家在线培训",
        Seller_Promotion: "卖家促销",
        Seller_Notification_Analytics: "卖家通知分析",
        Seller_Notification: "卖家通知",
        Seller_Marketplace_Notification: "卖家市场通知",
      },

      // 表单校验
      rules: {
        title: [{required: true, message: "标题不能为空", trigger: "blur"}],

        content: [{required: true, message: "内容不能为空", trigger: "blur"}],
      },
      que: null,
      checked1: false,
      keda: [
        {
          name: "哈哈",
          id: 1,
        },
        {
          name: "哇哇",
          id: 2,
        },
      ],
      dialogVisible: false,
      inputMsg: undefined,
      msgContent: [],

      huiData: [],
      dan: null,
      yonghu: [],
      kong: "zeng",
      bianid: null,
      daichid: null,
    };
  },

  created() {
    this.getgetHui();
    this.getkey();
  },
  methods: {
    gdaTes(e) {
      return gdaTe(e);
    },
    xinzz() {
      this.form = {};
      (this.dialogVisible = true), (this.kong = "zeng");
    },
    bianji(e) {
      this.kong = "bian";
      this.dialogVisible = true;
      this.form.title = e.title;
      this.form.content = e.content;
      this.bianid = e.templateId;
    },
    submitForm() {
      this.$refs["ruleForms"].validate((valid) => {
        if (valid) {
          xinjiala(this.yonghu.apiKey, this.yonghu.clientId, {
            posting_number: this.ruleForm.posting_number,
          });
        }
      });
    },
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let resq;
          if (this.kong == "zeng") {
            resq = zenkuai(this.form);
          } else if (this.kong == "bian") {
            let da = {
              ...this.form,
              templateId: this.bianid,
            };
            resq = putekui(da);
          }

          resq.then((response) => {
            if (response.code == 200) {
              this.getgetHui();
              this.form = {};
              this.dialogVisible = false;
              ElNotification({
                title: "提示",
                message: h("i", {style: "color: teal"}, "成功！"),
              });
            }
          });
        }
      });
    },
    markeds(ht) {
      return marked(ht);
    },
    // 删除快捷
    async dele(e) {
      const d = await deletekui(e.templateId);
      console.log(d);
      if (d.code == 200) {
        ElNotification({
          title: "提示",
          message: h("i", {style: "color: teal"}, "删除成功！"),
        });
        this.getgetHui();
      }
    },
    // 获取key
    async getkey() {
      const {rows} = await getshop();
      this.yonghu = rows[0];
      console.log(this.yonghu);
      this.getcLsit();
    },

    async getgetHui() {
      const {rows} = await getHui();
      this.huiData = rows;
    },
    daili(e) {
      this.que = e;
      this.daichid = e;

      this.getchatHistory(e);
    },
    async getchatHistory(id) {
      let e = {
        chat_id: id,
        direction: "Forward",
        from_message_id: 3000000000118032000,
        limit: 500,
      };
      const a = await chatHistory(this.yonghu.apiKey, this.yonghu.clientId, e);

      this.msgContent = a.messages;
      let yi = {
        chat_id: id,
        from_message_id: a.messages[0].message_id,
      };
      yidu(this.yonghu.apiKey, this.yonghu.clientId, yi);
      this.$nextTick(() => this.scrolltobottom());
    },
    addOtherMsg() {
      this.msgContent.push({
        isMe: false,
        content: this.inputMsg || "cscsscscscs",
      });
      this.inputMsg = "";

      this.$nextTick(() => this.scrolltobottom());
    },
    suijishu() {
      var Randnum = "";
      for (var i = 0; i < 10; i++) {
        Randnum += Math.floor(Math.random() * 10);
      }
      return Randnum;
    },

    fanyi(e) {
      const url = "https://api.fanyi.baidu.com/api/trans/vip/translate";
      const appid = "20240412002021671"; //appid
      const salt = this.suijishu();
      const secretKey = "zrLfSXZsjUTK4DKKDFPr"; //秘钥
      let str = appid + e + salt + secretKey;
      let sign = md5(str);
      jsonp(url, {
        q: e,
        from: "auto",
        to: "ru",
        appid: appid,
        salt: salt,
        sign: sign,
      })
        .then((res) => {
          this.dan = res.trans_result[0].dst;
          this.inputMsg = this.dan;
          console.log(this.inputMsg);
          this.fasongm();

          this.$nextTick(() => this.scrolltobottom());
        })
        .catch((err) => {
          console.log("err", err);
        });
    },

    // 获取聊天列表
    async getcLsit() {
      let e = {
        filter: {
          chat_status: "ALL",
          unread_only: true,
        },
        limit: 1000,
        offset: 0,
      };
      const a = await getCList(this.yonghu.apiKey, this.yonghu.clientId, e);
      if (a) {
        this.chatList = a.chats;
      }
    },
    async fasongm() {
      const df = {
        chat_id: this.daichid,
        text: this.inputMsg,
      };
      const a = await fasong(this.yonghu.apiKey, this.yonghu.clientId, df);
      this.inputMsg = "";
      this.getchatHistory(this.daichid);
    },
    transmitMsg(e, i = null) {
      console.log(i);
      if (i) {
        if (this.checked1) {
          this.fanyi(i);
        } else {
          this.inputMsg = i;
          this.fasongm();
        }

        this.$nextTick(() => this.scrolltobottom());
      }

      if (!this.inputMsg) return;

      if (this.checked1) {
        this.fanyi(this.inputMsg);
      } else {
        this.fasongm();
      }

      this.inputMsg = "";
      setTimeout(() => {
        this.$nextTick(() => this.scrolltobottom());
      }, 800);
      this.$nextTick(() => this.scrolltobottom());
    },
    scrolltobottom() {
      this.$refs.chatBox.scrollTop = this.$refs.chatBox.scrollHeight;
    },
  },
};
</script>

<style lang="scss" scoped>
.xin {
  font-size: 14px;
  cursor: pointer;
  &:hover {
    color: rgb(78, 168, 185);
  }
}
.box {
  ul {
    li {
      cursor: pointer;
      height: 35px;
      text-align: center;
      line-height: 35px;
      background: rgb(78 168 185);
      color: #fff;
    }
  }
}
.boxs {
  ul {
    height: 500px;
    overflow-x: scroll;
    .se {
      background: rgb(178, 185, 187);
      color: #fff;
      .ni {
        color: #fff !important;
      }
    }
    li {
      cursor: pointer;
      height: 50px;
      font-size: 12px;
      padding: 5px 0;

      text-align: center;
      // line-height: 40px;
      background: rgb(222, 222, 222);
      color: #020202;
      border-bottom: 1px solidrgb(206, 206, 206) 9;
      &:hover {
        background: rgb(193, 193, 193);
        color: #ffffff;
        .ni {
          color: #fff !important;
        }
      }
    }
  }
}

.chat_frame_box {
  width: 1000px;
  box-sizing: border-box;
  background: #f5f5f5;
  box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.06);
  border-radius: 6px;
  border: 1px solid #eceef0;

  .header {
    padding-left: 15px;
    display: flex;
    justify-content: flex-start;
    align-items: center;

    line-height: 30px;
    height: 30px;
    background: linear-gradient(180deg, #24c5ea 0%, #07cceb 100%) #42e8f4;
    border-radius: 8px 6px 0px 0px;
    font-size: 18px;
    font-weight: 500;
    color: #ffffff;

    .customer_service {
      width: 38px;
      height: 38px;
      margin-right: 10px;
    }
  }

  .chat_frame_body {
    height: calc(100% - 50px);
    display: flex;
    .left,
    .right {
      box-sizing: border-box;
      height: 456px;
    }
    .left {
      height: 100%;
      width: 80%;
      border-right: 1px solid #e8e8e8;
      display: grid;
      grid-template-rows: calc(100% - 150px) 1fr;
      background: #f5f5f5;

      .chat_box {
        box-sizing: border-box;
        overflow-y: scroll;
        box-sizing: border-box;
        padding: 10px 0px 20px 0px;
        width: 100%;
        border-bottom: 1px solid #e8e8e8;
        .msg_li {
          position: relative;
          margin-top: 16px;
          width: 100%;
          padding: 0px 100px 0px 58px;

          .head_img {
            width: 38px;
            height: 38px;
            position: absolute;
            left: 10px;
            top: 50%;
            transform: translateY(-50%);
          }

          .details {
            display: inline-block;
            padding: 10px 14px;
            background: #ffffff;
            border-radius: 0px 8px 8px 8px;
          }

          &.myself {
            padding: 0px 58px 0px 100px;
            &:after {
              content: "";
              display: block;
              clear: both;
            }
            .head_img {
              left: auto;
              right: 10px;
            }

            .details {
              float: right;
              background: #e4f2fe;
              border-radius: 8px 0px 8px 8px;
            }
          }
        }
      }

      .input_box {
        box-sizing: border-box;
        padding: 5px 13px 5px 15px;
        &:after {
          content: "";
          display: block;
          clear: both;
        }
        flex: 1;
        display: grid;
        grid-template-rows: 90px 1fr;
        width: 100%;

        ::v-deep .el-textarea__inner {
          padding: 0;
          height: 100%;
          border: none;
          &::-webkit-scrollbar-track-piece {
            // background: #d3dce6;
            background: rgb(250, 250, 250);
          }

          &::-webkit-scrollbar {
            width: 0px;
          }

          &::-webkit-scrollbar-thumb {
            // background: #99a9bf;
            background: rgb(192, 187, 181);

            border-radius: 20px;
          }

          background: #f5f5f5;
          cursor: pointer;
        }
        .btn_box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .maxlength_msg {
            font-size: 14px;
            font-family: SourceHanSansCN-Regular, SourceHanSansCN;
            font-weight: 400;
            color: #969799;
            line-height: 21px;
          }
          .submit_btn {
            width: 66px;
            height: 28px;
            background: #1675e8;
            border-radius: 6px;
          }
        }
      }

      :is(.chat-box)::-webkit-scrollbar {
        width: 0px;
      }
    }

    .right {
      box-sizing: border;
      padding: 20px 10px;
      width: 298px;
      overflow: hidden;
      background: rgb(255, 255, 255);
      .common_question_title {
        position: relative;
        height: 22px;
        font-size: 16px;
        font-weight: 600;
        color: #212222;
        line-height: 22px;
        &::after {
          content: "";
          position: absolute;
          bottom: -2px;
          left: 0;
          display: inline-block;
          width: 72px;
          height: 2px;
          background: linear-gradient(270deg, #ffffff 0%, #1675e8 100%);
          border-radius: 1px;
          opacity: 0.9;
        }
      }

      .question_list {
        box-sizing: border-box;
        padding: 20px 0px;
        list-style-type: initial;

        .li {
          display: flex;

          justify-content: space-between;
          position: relative;
          margin-bottom: 20px;
          text-indent: 1em;
          font-size: 14px;
          font-family: SourceHanSansCN-Regular, SourceHanSansCN;
          font-weight: 400;
          color: #212222;
          line-height: 21px;
          cursor: pointer;
          .hot_fill {
            width: 10px;
            height: 12px;
          }

          .tl {
            &:hover {
              color: rgb(78, 168, 185);
            }
          }
          .des {
            &:hover {
              color: rgb(78, 168, 185);
            }
          }
          &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            display: inline-block;
            border-radius: 50%;
            width: 4px;
            height: 4px;
            background: #cccccc;
          }
        }
      }
    }
  }
}

:deep(.el-textarea__inner) {
  box-shadow: none !important;
}
</style>
